
#include "laserspi.h"



const String BACK_CLEAR = "Hello";
spi_ring_buffer spi_buffer  =  { { 0 }, 0, 0 };

static void storeChar(unsigned char c);

LaserSPI::LaserSPI()
{
  
}

void LaserSPI::initSPI()
{
    pinMode(MISO, OUTPUT);
    SPCR |= _BV(SPE);
    SPCR |= _BV(SPIE);
}

void LaserSPI::writeChar(char c)
{
    SPDR = c;
    while (!(SPSR & (1 << SPIF)));
}

void LaserSPI::writeBuff(const char * str)
{
  while(*str)
    writeChar(*str++);
}

void LaserSPI::writeString(String str)
{
  writeBuff(str.c_str());
}

int LaserSPI::available(void)
{
  return (unsigned int)(RX_BUFFER_SIZE + spi_buffer.head - spi_buffer.tail )%RX_BUFFER_SIZE;
}

int LaserSPI::read(void)
{
  // if the head isn't ahead of the tail, we don't have any characters
  if (spi_buffer.head == spi_buffer.tail) 
  {
    return -1;
  } 
  else 
  {
    unsigned char c = spi_buffer.r_buffer[spi_buffer.tail];
    spi_buffer.tail = (unsigned int)(spi_buffer.tail + 1) % RX_BUFFER_SIZE;
    return c;
  }
}


void LaserSPI::flush()
{
  spi_buffer.head = spi_buffer.tail;
}

void LaserSPI::peek(void)
{
  if (spi_buffer.head == spi_buffer.tail) 
  {
    return -1;
  } else {
    return spi_buffer.r_buffer[spi_buffer.tail];
  }
}


void storeChar(unsigned char c)
{
  int i = (unsigned int)(spi_buffer.head + 1) % RX_BUFFER_SIZE;
  if (i != spi_buffer.tail) {
    spi_buffer.r_buffer[spi_buffer.head] = c;
    spi_buffer.head = i;
  }
}
//receive interrupter
ISR(SPI_STC_vect)
{
    char c = SPDR;
    storeChar(c);
}

